package com.ai.service.impl;

import lombok.AllArgsConstructor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ai.domain.po.ChatMessage;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class ChatMemoryImpl implements ChatMemory {

    private final RedisTemplate<String, Object> redisTemplate;
    //定义缓存的键
    private static final String BASIC_KEY = "chat:memory:";



    /*@Override
    public void add(String conversationId, List<Message> messages) {
        List<ChatMessage> chatMessages = new ArrayList<>();

        messages.forEach(message -> {
            ChatMessage chatMessage =
                    new ChatMessage(message.getMessageType().name().toLowerCase(),
                                                        message.getContent());
            chatMessages.add(chatMessage);
        });

        String key = BASIC_KEY + conversationId;
        // 将消息列表保存到 Redis 中,保存2天
        redisTemplate.opsForValue().set(key, chatMessages, Duration.ofDays(2));

    }*/
    @Override
    public void add(String conversationId, List<Message> messages) {
        String key = BASIC_KEY + conversationId;

        // 1. 从 Redis 获取已有消息
        @SuppressWarnings("unchecked")
        List<ChatMessage> existingMessages = (List<ChatMessage>) redisTemplate.opsForValue().get(key);

        List<ChatMessage> allMessages = new ArrayList<>();

        if (existingMessages != null) {
            allMessages.addAll(existingMessages); // 保留历史
        }

        // 2. 转换新消息并追加
        messages.forEach(message -> {
            ChatMessage chatMessage = new ChatMessage(
                    message.getMessageType().name().toLowerCase(),
                    message.getContent()
            );
            allMessages.add(chatMessage);
        });

        // 3. 重新保存整个列表（覆盖旧值，但内容包含历史+新消息）
        redisTemplate.opsForValue().set(key, allMessages, Duration.ofDays(2));
    }


    @Override
    public List<Message> get(String conversationId, int lastN) {
        String key = BASIC_KEY + conversationId;
        Object value = redisTemplate.opsForValue().get(key);

        if (value == null) {
            return Collections.emptyList();
        }

        // 安全地转换为 List<ChatMessage>
        List<ChatMessage> chatMessages;
        if (value instanceof List<?>) {
            chatMessages = ((List<?>) value)
                    .stream()
                    .filter(obj -> obj instanceof ChatMessage)
                    .map(obj -> (ChatMessage) obj)
                    .collect(Collectors.toList());
        } else {
            return Collections.emptyList();
        }

        // 转换为 Spring AI 的 Message
        return chatMessages.stream()
                .map(chatMsg -> {
                    String role = chatMsg.getRole();
                    String content = chatMsg.getContent();

                    if ("user".equalsIgnoreCase(role)) {
                        return new UserMessage(content);
                    } else if ("assistant".equalsIgnoreCase(role)) {
                        return new AssistantMessage(content);
                    } else if ("system".equalsIgnoreCase(role)) {
                        return new SystemMessage(content);
                    } else {
                        // 默认当作用户消息，或抛异常，或忽略
                        return new UserMessage(content);
                    }
                })
                .collect(Collectors.toList());

    }

    @Override
    public void clear(String conversationId) {
        redisTemplate.delete(BASIC_KEY + conversationId);
    }
}